import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 09 - 07
 * Time: 12:26
 */
//通过加锁来解决线程安全问题
public class Demo1 {
    private static int n = 0;//n要定义成全局变量
    public static void main(String[] args) throws InterruptedException {
        Object lock1 = new Object();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                synchronized(lock1) {
                    n++;
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                synchronized(lock1) {
                    n++;
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();//join一定要有，因为没有join的话t1和t2两个线程中count还没有自加主线程就已经打印n了
        t2.join();
        System.out.println(n);
    }
}
